var path = require('path');
var fs = require('fs');
var write = require('./backend/write');

var argvs = process.argv;
if (argvs.length >= 3) {
    var moduleName = argvs[2];
    var fileName = argvs[3] || moduleName;

    fs.stat(path.resolve(moduleName, `${fileName}.js`), function(err, stat) {
        if (err) {
            write(path.resolve(moduleName, `${fileName}.js`))
                .write(`(function (root, factory) {\n  typeof define === 'function' && define.amd ? define([], factory) :\n  root.${fileName} = factory();\n}(this, function () { 'use strict';\n\n  var ${fileName} = function() {}\n  return ${fileName}\n\n}))\n`);

            fs.stat(path.resolve(moduleName, `${fileName}.html`), function(err, stat) {
                if (err) {
                    write(path.resolve(moduleName, `${fileName}.html`))
                        .write(`<!DOCTYPE html>\n<html>\n  <head>\n    <meta charset="utf-8">\n    <meta id="viewport" name="viewport" content="width=device-width, initial-scale=1">\n    <title></title>\n    <script type="text/javascript" src="/assets/js/def.js"></script>\n    <script type="text/javascript" src="./${fileName}.js"></script>\n    \n  </head>\n  <body>\n    \n  </body>\n</html>\n`);
                } else {
                    console.log(`The module ${moduleName}/${fileName}.html has been exist.`);
                }
            });
        } else {
            console.log(`The module ${moduleName}/${fileName}.js has been exist.`);
        }
    });

} else {
    console.log("Usage: " + path.basename(argvs[0]) + " " + path.basename(argvs[1]) + " {module name} [file name]");
}